from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from libs.al_pay import alipay, gateway

from . import models
from .serializer import PayOrderSerializer
from utils.response import APIResponse


# class PayView(APIView):
#     def post(self, request, *args, **kwargs):
#         subject = "测试订单"
#
#         order_string = alipay.api_alipay_trade_page_pay(
#             out_trade_no="20161112",
#             total_amount=0.01,
#             subject=subject,
#             return_url="https://www.baidu.com",
#             notify_url="https://example.com/notify")
#
#         pay_url = gateway + '?' + order_string
#
#         return Response({'pay_url': pay_url})


class PayView(GenericViewSet, CreateModelMixin):
    queryset = models.Order.objects.all()
    serializer_class = PayOrderSerializer

    authentication_classes = [JSONWebTokenAuthentication, ]
    permission_classes = [IsAuthenticated, ]

    def create(self, request, *args, **kwargs):
        ser = self.get_serializer(data=request.data, context={'request': request})
        ser.is_valid(raise_exception=True)
        self.perform_create(ser)
        pay_url = ser.context['pay_url']

        return APIResponse(msg='订单创建成功', pay_url=pay_url)


from utils.logging import get_logger
logger = get_logger('pay')

class PaySuccessView(APIView):
    def get(self, request, *args, **kwargs):
        out_trade_no = request.GET.get('out_trade_no')
        res = models.Order.objects.filter(out_trade_no=out_trade_no, order_status=1).first()
        if res:
            return APIResponse(status=0, msg='支付成功')
        else:
            return APIResponse(status=1, msg='支付未成功')

    def post(self, request, *args, **kwargs):
        try:
            result_data = request.data.dict()
            out_trade_no = result_data.get('out_trade_no')
            signature = result_data.pop('sign')
            from libs import al_pay
            result = al_pay.alipay.verify(result_data, signature)
            if result and result_data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
                # 完成订单修改：订单状态、流水号、支付时间
                models.Order.objects.filter(out_trade_no=out_trade_no).update(order_status=1)
                # 完成日志记录
                logger.warning('%s订单支付成功' % out_trade_no)
                return Response('success')  # 必须返回给支付宝，否则会一直回调
            else:
                logger.error('%s订单支付失败' % out_trade_no)
        except:
            pass

        return Response('failed')
